package com.sysu.simulation;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sysu.simulation.bean.Clothes;
import com.sysu.simulation.bean.SimParams;
import com.sysu.simulation.bean.User;
import com.sysu.simulation.fragments.sim.SimBodyFragment;
import com.sysu.simulation.fragments.sim.SimEmptyFragment;
import com.sysu.simulation.fragments.sim.SimSubmitFragment;
import com.sysu.simulation.helper.AccountHelper;
import com.sysu.simulation.helper.ApiHelper;
import com.sysu.simulation.interfaces.SeriesFragment;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import cz.msebera.android.httpclient.Header;

public class SimFragment extends BaseFragment implements SimSubmitFragment.OnSimSubmitListener{

    @BindView(R.id.sim_title_text)
    TextView mTitle;
    @BindView(R.id.sim_left_nav_icon)
    ImageView mLeftNav;
    @BindView(R.id.sim_right_nav_icon)
    ImageView mRightNav;

    private FragmentManager fm;
    private int mContainerId;
    private Fragment mFragment;
    private Fragment mEmptyView;
    private Map<String, Fragment> pages;
    private SimParams mParams;
    private TextHttpResponseHandler mHandler;
    private static final String DEFAULT_TITLE = "仿真参数设置";

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(context instanceof MainActivity) {
            ((MainActivity)context).addOnBackPressedListener(new MainActivity.OnBackPressedListener() {
                @Override
                public boolean handleBackPressed() {
                    return isVisible() && onBackPressed();
                }
            });
        }
    }

    private boolean onBackPressed() {
        if(mFragment==null || mFragment instanceof SimEmptyFragment || mFragment instanceof SimBodyFragment) {
            return false;
        }
        else {
            mLeftNav.callOnClick();
            return true;
        }
    }

    @Override
    protected void initWidget(View root) {
        fm = getChildFragmentManager();
        mLeftNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mFragment instanceof SeriesFragment) {
                    changeToPage(((SeriesFragment)mFragment).getPreviousPage(), false);
                }
            }
        });
        mRightNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mFragment instanceof SeriesFragment) {
                    if(((SeriesFragment) mFragment).canMoveForward()) {
                        if(mFragment instanceof SimParamsSetter) {
                            ((SimParamsSetter) mFragment).setParams(mParams);
                        }
                        changeToPage(((SeriesFragment) mFragment).getNextPage(), true);
                    }
                }
            }
        });

        mHandler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                changeToPage(SimBodyFragment.class.getName(), false);
                if(mContext instanceof MainActivity) {
                    Bundle extra = new Bundle();
                    extra.putString("simresult",responseString);
                    RecordChartActivity.show(mContext, extra);
                    //((MainActivity)mContext).getBottomNav().doSelect(0, extra);
                }
            }
        };
    }

    @Override
    protected void initData() {
        pages = new HashMap<>();
        mContainerId = R.id.sim_content;
        mParams = new SimParams();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!AccountHelper.isLogin()) {
            if(mEmptyView==null) mEmptyView = Fragment.instantiate(getContext(), SimEmptyFragment.class.getName());
            addFragment(mEmptyView, false);
        }
        else {
            if(mFragment==null || mFragment instanceof SimEmptyFragment) {
                changeToPage(SimBodyFragment.class.getName(), false);
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_sim;
    }

    private void addFragment(Fragment newFragment, boolean needBackStack) {
        FragmentTransaction ft = fm.beginTransaction();
        if(mFragment != null) {
            ft.detach(mFragment);
        }
        if(newFragment != null) {
            if(!newFragment.isDetached()) {
                ft.add(mContainerId, newFragment, null);
            }
            else {
                ft.attach(newFragment);
            }
            mFragment = newFragment;
        }
        ft.commit();
        handleNavBar(mFragment);
    }

    private void handleNavBar(Fragment fragment) {
        if(fragment instanceof SeriesFragment) {
            SeriesFragment seriesFragment = (SeriesFragment) fragment;
            mLeftNav.setVisibility(seriesFragment.getPreviousPage()==null ? View.INVISIBLE : View.VISIBLE);
            mRightNav.setVisibility(seriesFragment.getNextPage()==null ? View.INVISIBLE : View.VISIBLE);
            mTitle.setText(seriesFragment.getNavTitle());
        }
        else {
            mLeftNav.setVisibility(View.INVISIBLE);
            mRightNav.setVisibility(View.INVISIBLE);
            mTitle.setText(DEFAULT_TITLE);
        }
    }

    private void changeToPage(String newPage, boolean needBackStack) {
        if (newPage != null) {
            if (!pages.containsKey(newPage)) {
                pages.put(newPage, Fragment.instantiate(getContext(), newPage));
            }
            addFragment(pages.get(newPage), needBackStack);
        }
    }

    @Override
    public void onSimSubmit() {
        String paramString = new Gson().toJson(mParams);
        ApiHelper.sim(AccountHelper.getUserId(), paramString, mHandler);
    }

    public interface SimParamsSetter {
        void setParams(SimParams params);
    }
}
